#include "app_event_dispatcher.h"
#include <QByteArray>
#include <QApplication>
#include <QAbstractNativeEventFilter>
#include <QTime>
#include <QDebug>
#ifdef Q_OS_WIN
    #include <windows.h>
    #pragma comment(lib, "user32.lib")
#endif

const uint DOUBLE_CTRL_INTERVAL = 2;

AppEventDispathcer::AppEventDispathcer(MainWindow *mainWindow)
{
    this->mainWindow = mainWindow;
}

bool AppEventDispathcer::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
     if (eventType == "windows_generic_MSG" || eventType == "windows_dispatcher_MSG")
    {
#ifdef Q_OS_WIN
        MSG *pMsg = static_cast<MSG*>(message);

        if (pMsg->message == WM_KEYDOWN)
        {
            ProcessKeyDown(pMsg->wParam);
        }
        else if (pMsg->message == WM_KEYUP)
        {
            ProcessKeyUp(pMsg->wParam);
        }
    }
#endif

    return false;
}

void AppEventDispathcer::ProcessKeyDown(WPARAM wParam)
{
    switch (wParam) {
    case VK_CONTROL:
        OnCtrlKeyDown();
        break;
    }
}

void AppEventDispathcer::ProcessKeyUp(WPARAM wParam)
{
    switch (wParam) {
    case VK_CONTROL:
        OnCtrlKeyUp();
        break;
    }
}


void AppEventDispathcer::OnCtrlKeyDown()
{
    qDebug() << "OnCtrlKeyDown" << endl;
    uint curTime = QDateTime::currentDateTime().toTime_t();
    if (curTime - lastCtrlPressTime < DOUBLE_CTRL_INTERVAL)
        qDebug() << "双ctrl" << endl;
    lastCtrlPressTime = curTime;
    isCtrlPressing = true;
}

void AppEventDispathcer::OnCtrlKeyUp()
{
    qDebug() << "OnCtrlKeyUp" << endl;
    isCtrlPressing = false;
}

void AppEventDispathcer::OnDoubleClickCtrlKey()
{
    if (this->mainWindow->isHidden())
        this->mainWindow->show();
}
